/*
 * Created on 07-feb-2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.juanfrivaldes.cio2005.web;

import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * @author root
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class VerDocumentoAction extends PrivateAction {
	
	private final static String resumenesPath="/cio2005-resumenes/";
	private final static String showResumenesPath="/WEB-INF/files/resumenes/";
	
	private final static String ponenciasPath="/cio2005-ponencias/";
	private final static String showPonenciasPath="/WEB-INF/files/ponencias/";
	
	private static Log log = LogFactory.getLog(VerDocumentoAction.class);

	private void copyFile(String from, String to) throws IOException {
			FileInputStream stream = new FileInputStream(from);

			OutputStream bos = new FileOutputStream(to);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			stream.close();
			bos.close();

	}

	private boolean existsFile(String path) throws IOException {
		File file=new File(path);
		return file.isFile();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.juanfrivaldes.cio2005.web.BaseAction#protectedExecute(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	protected ActionForward protectedExecute(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		VerDocumentoForm verForm = (VerDocumentoForm) form;
		log.trace("Accion invocada: " + request.getParameter("action"));
		
		log.trace("Solicitud de ver documento tipo " + verForm.getTipo()
				+ "- id " + verForm.getId());
		
		String path="",showPath="";
		
		if(verForm.getTipo().equals("resumen")){
			path=resumenesPath;
			showPath=showResumenesPath;
		}
		else{
			path=ponenciasPath;
			showPath=showPonenciasPath;
		}
		
		String fileName=verForm.getId()+".pdf";
		
		String newFile=getServlet().getServletContext().getRealPath(showPath+fileName);
				
		
		if (!existsFile(newFile)){
			log.trace("El fichero "+newFile+" no existe, lo creamos");
			copyFile(path+fileName,newFile);
		}
		else{
			log.trace("El fichero"+newFile+" ya existe, lo usamos");
		}
		log.trace("Escrito fichero "+newFile);
		return new ActionForward(showPath+fileName);
	}

}
